//
//  ZSUserAccountViewModel.swift
//  ZSWeibo
//
//  Created by zsj1992 on 16/4/10.
//  Copyright © 2016年 ichange. All rights reserved.
//

import UIKit


class ZSUserAccountViewModel: NSObject {
    
    var userAccount:ZSUserAccount?
    

    var userLogin:Bool{

        if let _ = userAccount where userAccount?.expires_date? .compare(NSDate()) == NSComparisonResult.OrderedDescending {
        
            return true
        }
    userAccount = nil
    
    return false
    }


    //提供一个单例对象
    static let sharedUserViewModel:ZSUserAccountViewModel = ZSUserAccountViewModel()
    
    //私有化构造方法
    override private init() {
        super.init()

        userAccount = self.readUserAccountData()
    }
    
    
    
    /**获取授权的方法*/
    func loadAccessToken(code:String,finished:(isSuccess:Bool)->()){
        
        ZSNetworkTools.sharedTools.loadAccessToken(code) { (result, error) -> () in

            if error != nil{
            print(error)
            return
            }
            
            //到这就是请求授权成功,通过token进行用户数据的请求
            self.loadUserData(result!, finished: finished)
        }
        
    }
    
    
    
    

    func loadUserData(result: AnyObject,finished:(isSuccess:Bool)->()){

        guard let dict = result as? [String: AnyObject] else {
            return
        }

        ZSNetworkTools.sharedTools.loadUserData(dict,result: result) { (result, error) -> () in
            if error != nil{
                finished(isSuccess: false)
                print(error)
                return
            }

            guard var dict1 = result as? [String:AnyObject] else{
                return
            }

            //拼接
            for (k,v) in dict{
                
                dict1[k] = v
            }
            
            self.saveUserData(dict1)

            finished(isSuccess: true)
        }
    }
}
    


extension ZSUserAccountViewModel{
    
    func saveUserData(result:[String:AnyObject]){

        //创建一个模型对象
        let userAccount = ZSUserAccount(dic: result)
        
        print(userAccount)
        
        self.userAccount = userAccount
        
        let keys = ["access_token","avatar_large","name","expires_in","uid"]

        let dic = userAccount.dictionaryWithValuesForKeys(keys)
        
        let ud = NSUserDefaults.standardUserDefaults()
        
        ud.setObject(dic, forKey: "userAccount.plist")
        
        ud.synchronize()
    }

    
    func readUserAccountData()->(ZSUserAccount?){
    
        
        if userAccount != nil{
            
        return userAccount!

        }

        let ud = NSUserDefaults.standardUserDefaults()
        
        let x = ud.objectForKey("userAccount.plist")
        
        guard let dic = x as? [String:AnyObject] else{
            
            return nil
        }
        

      return ZSUserAccount(dic: dic)

    }

}